<template>
  <div>
    <el-container>
      <el-main>
        <div class="mbx p-4">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>添加文档</el-breadcrumb-item>
          </el-breadcrumb>
        </div>

        <div class="mbx mt-4 p-4">
          <el-form ref="form" :model="form">
            <el-form-item>
              <el-input v-model="form.title" placeholder="输入标题"></el-input>
            </el-form-item>

            <div class="box"><div id="editor"></div></div>

            <hr />
            <h4>文档预览：</h4>
            <div class="preview" v-html="editorData"></div>
            <hr />
            <el-form-item>
              <el-button type="primary" @click="getEditorData">提交</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import wangEditor from "wangeditor";
export default {
  inject: ["reload"],
  data() {
    return {
      editor: null,
      editorData: "",
      form: {
        title: "",
      },
    };
  },
  mounted() {
    this.initEditor();
  },

  beforeDestroy() {
    // 调用销毁 API 对当前编辑器实例进行销毁
    this.editor.destroy();
    this.editor = null;
  },

  methods: {
    // 初始化插件
    initEditor() {
      const editor = new wangEditor("#editor");
      editor.config.placeholder = "请输入内容";
      editor.config.onchangeTimeout = 0;
      editor.config.uploadImgShowBase64 = true;
      // 配置 onchange 回调函数，将数据同步到 vue 中
      editor.config.onchange = (res) => {
        this.editorData = res;
      };
      // 创建编辑器
      editor.create();
      this.editor = editor;
    },

    // 获取编辑器内容
    getEditorData() {
      var params = new URLSearchParams();
      var data = this.editor.txt.html();
      params.append("title", this.form.title);
      params.append("html", data);
      this.$axios
        .post("http://127.0.0.1/user/adminadd", params)
        .then((res) => {
          if (res.data.status == 200) {
            this.$message({
              message: "提交成功！",
              type: "success",
            });
            this.reload();
          } else {
            this.$message.error("添加失败！");
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
};
</script>

<style>
#editor {
  z-index: 99;
}
</style>